package com.solidtrust.web.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.solidtrust.common.FreePersister;
import com.solidtrust.entity.Area;
import com.solidtrust.entity.Build;
import com.solidtrust.entity.CarImage;
import com.solidtrust.entity.Model;
import com.solidtrust.entity.web.Dealer;
import com.solidtrust.entity.web.DealerReview;
import com.solidtrust.repository.AreaRepository;
import com.solidtrust.repository.BuildRepository;
import com.solidtrust.repository.DealerRepository;
import com.solidtrust.repository.DealerReviewRepository;
import com.solidtrust.repository.GanjiRepository;
import com.solidtrust.repository.ModelRepository;
import com.solidtrust.repository.VolumeRepository;

@Controller
public class WebController {
	
	private static final Logger log4j = Logger.getLogger(WebController.class);
	
	private static final Integer MAX_MILEAGE = 9999999;
	private static final Integer _5000 = 5000;
	private static final Float LEFT_RATE = 0.6f;
	private static final Float RIGHT_RATE = 1.5f;

	@Autowired FreePersister free;
	@Autowired GanjiRepository ganjiRep;
	@Autowired AreaRepository areaRep;
	@Autowired VolumeRepository volRep;
	@Autowired ModelRepository modelRep;
	@Autowired BuildRepository buildRep;
	@Autowired DealerRepository dealerRep;
	@Autowired DealerReviewRepository dealerReviewRep;
	
	
	@RequestMapping("/")
	public String home(){
		return "web/home.jsp";
	}
	@RequestMapping("/p")
	public String carPrice(){
		return "web/car_price.jsp";
	}
	
	@RequestMapping("/pr")
	public String ganjiPrice(@RequestParam(value="area", required = false) Integer area,
			@RequestParam(value="build") Integer _build,
			@RequestParam(value="volume", required = false) Integer volume,
			@RequestParam(value="mileage") Integer _mileage,
			org.springframework.ui.Model _m){
		
		Date from = DateUtils.addMonths(new Date(), -10);
		
		//mileage
		int start = 0, end = MAX_MILEAGE;
		if(_mileage != null){
			int mileage = _mileage * 1000;
			if(mileage < _5000){
				end = _5000;
			}else{
				start = (int)(mileage * LEFT_RATE);
				end = (int)(mileage * RIGHT_RATE);
			}
		}
		
		Build b = buildRep.findOne(_build);
		Model m = b.getModel();
		String model = m.getModel();
		String brand = m.getBrand().getBrand();
		String build = b.getBuild();
		String p2 = brand,
				p3 = model,
				p4 = build;
		Integer averageByCity = 0, averageByProvince = 0, average = 0;
		if(area != null && area != 0){
			Area c = areaRep.findOne(area);
			_m.addAttribute("area", c.getName());
			_m.addAttribute("_area", area);
			List<String> cities = areaRep.getCitiesInSameProvince(area);
			
			String p1 = c.getNameOfGanji();
					
			
			if(volume != null && volume != 0){
				averageByCity = ganjiRep.averageByCity(p1, p2, p3, p4, 
							volume, from, start, end);
				averageByProvince = ganjiRep.averageByCities(cities, p2, p3, p4, 
						volume, from, start, end);
			}else{
				averageByCity = ganjiRep.averageByCity1(p1, p2, p3, p4, 
						from, start, end);
				averageByProvince = ganjiRep.averageByCities1(cities, p2, p3, p4, 
					from, start, end);
			}
		}
		if(volume != null && volume != 0){
			average = ganjiRep.average(p2, p3, p4, volume, from, start, end);
		}else{
			average = ganjiRep.average1(p2, p3, p4, from, start, end);
		}
		
		//averageByCity = 0, averageByProvince = 0, average = 0
		_m.addAttribute("averageByCity", averageByCity);
		_m.addAttribute("averageByProvince", averageByProvince);
		_m.addAttribute("average", average);
		_m.addAttribute("brand", brand);
		_m.addAttribute("mileage", _mileage);
		_m.addAttribute("model", model);
		_m.addAttribute("build", build);
		_m.addAttribute("_build", _build);
		_m.addAttribute("volume", volume);
		
		CarImage image = m.getImage();
		if(image != null && image.getImage1() != null){
			_m.addAttribute("img", image.getImage1());
		}
		return "web/car_price_result.jsp";
	}
	
	@RequestMapping("/r")
	public String sellerReview(@RequestParam(value="p", required=false, defaultValue="1") Integer pageIndex, 
			org.springframework.ui.Model model){
		Pageable pageable = new PageRequest(pageIndex - 1, 50);
		Page<Dealer> dealers = dealerRep.findAll(pageable);
		for (Dealer dealer : dealers) {
			String n = dealer.getSellerName();
			try {
				System.out.println(new String(n.getBytes("gb2312"), "gbk"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		model.addAttribute("page", dealers);
		return "web/seller_review.jsp";
	}
	
	@RequestMapping("/d/{id}/{name}")
	public String sellerDetail(@PathVariable("id") Integer id,
			@PathVariable("name") String name, 
			org.springframework.ui.Model model){
		Dealer d = dealerRep.findOne(id);
		model.addAttribute("d", d);
		List<DealerReview> list = dealerReviewRep.findByDealerOrderByIdDesc(d);
		model.addAttribute("reviews", list);
		Double score = list.stream().mapToInt(r->r.getScore()).average().orElse(0);
		model.addAttribute("offset", Math.round(score / 5));
		
		return "web/seller.jsp";
	}
	
	@RequestMapping(value = "/c/{id}", method = RequestMethod.POST)
	public String comment(@PathVariable("id") Integer id,
			Integer score, String comments,
			HttpServletRequest req, 
			org.springframework.ui.Model model){
		Dealer d = dealerRep.findOne(id);
		DealerReview dr = new DealerReview();
		dr.setComments(comments);
		dr.setDate(new Date());
		dr.setDealer(d);
		dr.setScore(score);
		dr.setName(req.getHeader("x-real-ip"));
		dealerReviewRep.save(dr);
		return "redirect:/d/" + id + "/~";
	}
	
	@RequestMapping("/faq")
	public String faq(){
		return "web/faq.jsp";
	}
	@RequestMapping("/c")
	public String contact(){
		return "web/contact.jsp";
	}
}
